package com.gujiangbo.application.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class InternetProtocolTool {
	private static Log log = LogFactory.getLog(InternetProtocolTool.class);

	public static String getRemoteAddr(HttpServletRequest request) {
		try {
			String remoteAddr = request.getHeader("X-Forwarded-For");
			if ((isEffective(remoteAddr)) && (remoteAddr.indexOf(",") > -1)) {
				String[] array = remoteAddr.split(",");
				String[] arrayOfString1;
				int j = (arrayOfString1 = array).length;
				for (int i = 0; i < j; i++) {
					String element = arrayOfString1[i];
					if (isEffective(element)) {
						remoteAddr = element;
						break;
					}
				}
			}
			if (!isEffective(remoteAddr)) {
				remoteAddr = request.getHeader("X-Real-IP");
			}
			if (!isEffective(remoteAddr)) {
			}
			return request.getRemoteAddr();
		} catch (Exception e) {
			log.error("get romote ip error,error message:" + e.getMessage());
		}
		return "";
	}

	public static Long getRemotePort(HttpServletRequest request) {
		try {
			String port = request.getHeader("remote-port");
			if (StringUtils.isNotEmpty(port)) {
				try {
					return Long.valueOf(Long.parseLong(port));
				} catch (NumberFormatException ex) {
					log.error("convert port to long error , port: " + port);
					return Long.valueOf(0L);
				}
			}
			return Long.valueOf(0L);
		} catch (Exception e) {
			log.error("get romote port error,error message:" + e.getMessage());
		}
		return Long.valueOf(0L);
	}

	private static boolean isEffective(String remoteAddr) {
		boolean isEffective = false;
		if ((remoteAddr != null) && (!"".equals(remoteAddr.trim()))
				&& (!"unknown".equalsIgnoreCase(remoteAddr.trim()))) {
			isEffective = true;
		}
		return isEffective;
	}

	public static String getRemoteIpMethod() throws AxisFault {
		MessageContext curContext = MessageContext.getCurrentContext();

		String remoteIp = "Unknown";
		if (curContext != null) {
			Object ipProperty = curContext.getProperty("remoteaddr");
			remoteIp = ipProperty.toString();
		}
		return remoteIp;
	}
}
